<!--
  * 代理商表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-26 06:40:44
-->
<template>
  <a-modal
    :title="form.id ? '商户信息修改' : '新增商户'"
    :width="1200"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-row>
        <a-col v-if="form.id !== undefined" :span="12">
          <span>登录账号：{{ form.no }}</span>
        </a-col>
        <a-col v-if="form.id !== undefined" :span="12">
          <span>公司简称：{{ form.companyAbbrName }}</span>
        </a-col>
        <a-col :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-500' }">基本信息</group-title>
        </a-col>
        <a-col :span="12">
          <a-form-item label="公司名称" name="companyName">
            <a-input style="width: 95%" v-model:value="form.companyName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col v-if="form.id === undefined" :span="12">
          <a-form-item label="公司简称" name="companyAbbrName">
            <a-input style="width: 95%" v-model:value="form.companyAbbrName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人" name="name">
            <a-input style="width: 95%" v-model:value="form.name" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系方式" name="phone">
            <a-input-number style="width: 95%" v-model:value="form.phone" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="城市" name="areaCode">
            <area-cascader style="width: 95%" v-model:value="form.areaCode" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="地址" name="addr">
            <a-input style="width: 95%" v-model:value="form.addr" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="授权业务" name="authBussType">
            <a-select v-model:value="form.authBussType" width="95%" :options="AUTH_BUSS_TYPE" placeholder="请选择授权业务" />
            <!-- <SmartEnumSelect width="95%" v-model:value="form.authBussType" enumName="ZZB_MERCHANT_AUTH_BUSS_TYPE_ENUM" placeholder="请选择" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <SmartEnumSelect width="95%" v-model:value="form.status" enumName="ZZB_NO_STATUS_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户业务人员" name="exhibitionId">
            <ExhibitionPageSelect
              style="width: 95%"
              ref="exhibitionSelect"
              placeholder="请选择开户业务人员"
              width="95%"
              :initParams="{ id: form.exhibitionId }"
              v-model:value="form.exhibitionId"
              :leaveFlag="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-input style="width: 95%" v-model:value="form.remark" placeholder="请输入" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-if="form.id === undefined">
        <a-col :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-500' }"
            >账号设置（<span class="text-#F59A23">账号设置为手机号的，将推送验证，登录成功后该账号生效</span>）</group-title
          >
        </a-col>
        <a-col :span="12">
          <a-form-item label="账号类型" name="noType">
            <SmartEnumSelect width="95%" enum-name="ZZB_NO_TYPE_ENUM" v-model:value="form.noType" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 登录账号" name="no" help="注意：非手机号账号类型，需大于或小于11位">
            <a-input style="width: 95%" v-model:value="form.no" placeholder="请输入账号" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="密码" name="pwd">
            <a-input-password style="width: 95%" :maxlength="20" v-model:value="form.pwd" v-model:visible="visiblePwd" placeholder="请输入密码" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="密码确认" name="conPwd">
            <a-input-password
              style="width: 95%"
              :maxlength="20"
              v-model:value="form.confirmPwd"
              v-model:visible="visibleConfirmPwd"
              placeholder="请再次输入密码"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template></a-modal
  >
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { merchantApi } from '/@/api/business/b-operation/merchant/merchant-api'
  import { smartSentry } from '/@/lib/smart-sentry'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import AreaCascader from '/@/components/business/b-operation/area-cascader/index.vue'
  import ExhibitionPageSelect from '/@/components/business/b-agent/exhibition-page-select/index.vue'
  import { isMulPassword } from '/@/utils/validate'
  import {
    AUTH_BUSS_TYPE, //授权业务类型
    ZZB_MCH_NO_STATUS, //商户状态
  } from '/@/constants/dict'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visiblePwd = ref(false)
  const visibleConfirmPwd = ref(false)

  function show(rowData) {
    Object.assign(form, formDefault)
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData)
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    nextTick(() => {
      formRef.value.clearValidate()
    })
  }

  function onClose() {
    Object.assign(form, formDefault)
    visibleFlag.value = false
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    id: undefined,
    no: undefined, //商户账号
    noType: undefined, //商户账号
    pwd: undefined, //商户密码
    confirmPwd: undefined, //商户密码
    companyName: undefined, //公司名称
    companyAbbrName: undefined, //公司简称
    name: undefined, //联系人
    phone: undefined, //联系方式
    areaCode: undefined, //城市，所属区/县ID
    addr: undefined, //地址
    authBussType: undefined, //授权业务，0全部，1开设代理商，2开商户
    status: undefined, //状态，0正常使用，1禁止开代理商，2禁止开商户，3禁止操作人员登录，4系统停止使用，5停止全部收款，6全部禁用
    exhibitionId: undefined, //开户业务人员
    // profitDrawType: undefined, //分润提现，0统一提现，1逐级提现
  }

  let form = reactive({ ...formDefault })

  // 密码复杂度校验
  const validatePasswordComplexity = (rule, value, callback) => {
    if (!value) {
      callback()
      return
    }

    // 定义四种字符类型
    const hasLowercase = /[a-z]/.test(value)
    const hasUppercase = /[A-Z]/.test(value)
    const hasNumber = /\d/.test(value)
    const hasSpecial = /[@#$%^&*()_+\-=]/.test(value)

    // 计算满足的条件数量
    const count = [hasLowercase, hasUppercase, hasNumber, hasSpecial].filter(Boolean).length

    if (count >= 3) {
      callback()
    } else {
      callback(new Error('必须包含大小写字母、数字、特殊符号中至少三种'))
    }
  }

  // 确认密码校验
  const validateConfirmPassword = (rule, value, callback) => {
    if (value !== form.pwd) {
      callback(new Error('两次输入的密码不一致'))
    } else {
      callback()
    }
  }

  const rules = {
    no: [{ required: true, message: '登录账号 必填' }],
    noType: [{ required: true, message: '账号类型 必填' }],
    pwd: [
      { required: true, message: '请输入密码' },
      { min: 8, message: '密码长度至少8位' },
      { max: 20, message: '密码长度最多20位' },
      { validator: validatePasswordComplexity },
      {
        validator: isMulPassword,
      },
    ],
    confirmPwd: [
      { required: true, message: '请确认密码' },
      { validator: validateConfirmPassword },
      {
        validator: isMulPassword,
      },
    ],
    companyName: [{ required: true, message: '公司名称 必填' }],
    companyAbbrName: [{ required: true, message: '公司简称 必填' }],
    name: [{ required: true, message: '联系人 必填' }],
    phone: [{ required: true, message: '联系方式 必填' }],
    areaCode: [{ required: true, message: '城市 必填' }],
    addr: [{ required: true, message: '地址 必填' }],
    authBussType: [{ required: true, message: '授权业务 必填' }],
    status: [
      {
        required: true,
        message: '状态 必填',
      },
    ],
    profitDrawType: [{ required: true, message: '分润提现 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      if (form.id) {
        await merchantApi.update(form)
      } else {
        await merchantApi.insert(form)
      }
      message.success('操作成功')
      emits('reloadList')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )

  defineExpose({
    show,
  })
</script>
